﻿using HY.Common;
using HY.Model;
using HY.Service;
using HY.Web.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Security.Claims;

namespace HY.Web.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController(ILogger<HomeController> logger) : base(logger)
        {
        }

        [Authorize]
        public IActionResult Index()
        {
            string roleId = User.FindFirstValue(SystemConst.CookieKey.RoleId);
            string userName = User.FindFirstValue(SystemConst.CookieKey.UserName);
            List<LeftMenuModel> leftMenuModels = new();
            IEnumerable<SysResource> resourceList = GlobalClass.GetSysResourceList().Where(w => w.ResourceState == true && w.ResourceType == 1);
            if (roleId != "0" || (userName != "admin" && userName != "hengke"))
            {
                SysRole sysRole = GlobalClass.GetSysRoleList().FirstOrDefault(f => f.Id == int.Parse(User.FindFirstValue(SystemConst.CookieKey.RoleId)));
                resourceList = resourceList.Where(w => ("," + sysRole.ResourceIds + ",").Contains($",{w.Id},"));
            }
            ViewBag.ResourceList = JsonConvert.SerializeObject(GetLeftMenuList(resourceList, 0), new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            return View();
        }
        /// <summary>
        /// 获取菜单所需格式数据
        /// </summary>
        /// <param name="resourceList"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<LeftMenuModel> GetLeftMenuList(IEnumerable<SysResource> resourceList, long parentId)
        {
            return resourceList.Where(w => w.ParentId == parentId).Select(s => new LeftMenuModel() { Title = s.ResourceName, Href = s.ResourceUrl, Icon = s.ResourceIcon, Child = GetLeftMenuList(resourceList, s.Id) }).ToList();
        }

        public IActionResult Desktop()
        {
            return View();
        }

        #region 登录注销

        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Login(string username, string password)
        {
            password = StringHelper.MD5Encrypt(password);
            SysUser user = DbContext.SysUser.GetFirst(u => u.UserName == username && u.Password == password && u.IsDelete == false);
            if (user == null)
            {
                returnModel.Code = 0;
                returnModel.Message = "登录失败!";
            }
            else
            {
                var claims = new List<Claim>()
                {
                    new Claim(SystemConst.CookieKey.UserId,user.Id.ToString()),
                    new Claim(SystemConst.CookieKey.UserName,user.UserName),
                    new Claim(SystemConst.CookieKey.RoleId,user.RoleId.ToString()??""),
                };
                ClaimsPrincipal claimsPrincipal = new(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal,
                    new AuthenticationProperties
                    {
                        //IsPersistent = true
                    }).Wait();
            }
            return Json(returnModel);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public IActionResult LogOut()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Home");
        }
        #endregion

        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="id">接收状态码(404:请求Url不存在(包括请求地址及静态资源文件);)</param>
        /// <returns></returns>
        public IActionResult Error(int id)
        {
            int statusCode = id;
            string requestType = HttpContext.Request.Headers["X-Requested-With"];
            var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
            if (statusCode != 403 && statusCode != 404) statusCode = HttpContext.Response.StatusCode;

            string message = $"代码:{statusCode},地址:{statusCodeResult?.OriginalPath},{exceptionDetails?.Error}";

            if (!string.IsNullOrEmpty(requestType) && requestType.Equals("XMLHttpRequest", StringComparison.CurrentCultureIgnoreCase))
            {
                returnModel.Code = statusCode;
                returnModel.Message = $"请求错误，代码{statusCode}";
                logger.LogError("Ajax请求-{message}", message);
                HttpContext.Response.ContentType = "application/json;charset=utf-8";
                HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                return Json(returnModel);
            }

            logger.LogError("{message}", message);
            ViewBag.statusCode = statusCode;
            ViewBag.message = $"请求错误，代码{statusCode}";
            return View(ViewBag);
        }
    }
}